package com.sunshine.lnuplus.model.Timetable;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import java.util.List;

public class TimetableRespository {
    private LiveData<List<TimetableEntity>> allLessonLive;
    private TimetableDao timetableDao;

    public TimetableRespository(Context context){
        TimetableDatabase database = TimetableDatabase.getDatabase(context);
        timetableDao = database.getTimetableDao();
        allLessonLive = timetableDao.getAllLessonLive();
    }

    public void insertLesson(TimetableEntity...timetableEntities){
        new TimetableRespository.InsertAsyncTask(timetableDao).execute(timetableEntities);
    }

    public void updateLesson(TimetableEntity...timetableEntities){
        new TimetableRespository.UpdateAsyncTask(timetableDao).execute(timetableEntities);
    }

    public void deleteLesson(TimetableEntity...timetableEntities){
        new TimetableRespository.DeleteAsyncTask(timetableDao).execute(timetableEntities);
    }

    public void deleteAllLesson(){
        new TimetableRespository.DeleteAllAsyncTask(timetableDao).execute();
    }

    public LiveData<List<TimetableEntity>> getAllLessonLive() {
        return allLessonLive;
    }

    static class InsertAsyncTask extends AsyncTask<TimetableEntity,Void,Void>{
        private TimetableDao timetableDao;

        InsertAsyncTask(TimetableDao timetableDao){
            this.timetableDao = timetableDao;
        }

        @Override
        protected Void doInBackground(TimetableEntity... timetableEntities) {
            timetableDao.insertLesson(timetableEntities);
            return null;
        }
    }

    static class UpdateAsyncTask extends AsyncTask<TimetableEntity,Void,Void>{
        private TimetableDao timetableDao;

        UpdateAsyncTask(TimetableDao timetableDao){
            this.timetableDao = timetableDao;
        }

        @Override
        protected Void doInBackground(TimetableEntity... timetableEntities) {
            timetableDao.updateLesson(timetableEntities);
            return null;
        }
    }

    static class DeleteAsyncTask extends AsyncTask<TimetableEntity,Void,Void>{
        private TimetableDao timetableDao;

        DeleteAsyncTask(TimetableDao timetableDao){
            this.timetableDao = timetableDao;
        }

        @Override
        protected Void doInBackground(TimetableEntity... timetableEntities) {
            timetableDao.deleteLesson(timetableEntities);
            return null;
        }
    }

    static class DeleteAllAsyncTask extends AsyncTask<Void,Void,Void>{
        private TimetableDao timetableDao;

        DeleteAllAsyncTask(TimetableDao timetableDao){
            this.timetableDao = timetableDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            timetableDao.deleteAllLesson();
            return null;
        }
    }
}
